
//
//  AppDelegate.swift
//  网易新闻
//
//  Created by wl on 15/11/11.
//  Copyright © 2015年 wl. All rights reserved.
//

import UIKit
import IQKeyboardManagerSwift
import SVProgressHUD
//网络监测
var reachability: Reachability?
//判断是否重连后的网络
var isNetwork: Bool = false

//归档的全局路径
var userAccountPath: String = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0].stringByAppendingString("/userAccount.data")

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate{

    var window: UIWindow?
   
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        UITabBar.setupStyle()
        UINavigationBar.setupStyle()
        setHUDStyle()
        IQKeyboardManager.sharedManager().enable = true
               
        
       
        //网络状态监测
        do {
            reachability = try Reachability.reachabilityForInternetConnection()
            
        } catch {
            SVProgressHUD.showInfoWithStatus("无法识别当前网络")
        }
        if reachability!.isReachableViaWiFi() {
            
            NSUserDefaults.standardUserDefaults().setBool(true, forKey:"iswifi")
            //SVProgressHUD.showInfoWithStatus("连接类型：WiFi")
            NSUserDefaults.standardUserDefaults().synchronize()

        } else if reachability!.isReachableViaWWAN() {
            
            NSUserDefaults.standardUserDefaults().setBool(false, forKey:"iswifi")
            //SVProgressHUD.showInfoWithStatus("连接类型：移动网络")
            NSUserDefaults.standardUserDefaults().synchronize()

        } else {
           // SVProgressHUD.showInfoWithStatus("连接类型：没有网络连接")
        }
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AppDelegate.reachabilityChanged(_:)), name: ReachabilityChangedNotification, object: reachability)
        
        do {
            
            try reachability?.startNotifier()
            
        } catch {
           
            SVProgressHUD.showInfoWithStatus("无法识别当前网络")
        }

        
        //友盟推送
        UMessage.startWithAppkey(k_UMENG_KEY, launchOptions: launchOptions)
        
            let action1 = UIMutableUserNotificationAction();
            action1.identifier = "action1_identifier"
            action1.title = "Accept"
            action1.activationMode = UIUserNotificationActivationMode.Foreground//当点击的时候启动程序
            
            let action2 = UIMutableUserNotificationAction();//第二按钮
            action2.identifier = "action2_identifier"
            action2.title = "Reject"
            action2.activationMode = UIUserNotificationActivationMode.Background
            action2.authenticationRequired = true
            action2.destructive = true
            
            let categorys = UIMutableUserNotificationCategory();
            categorys.identifier = "category1";//这组动作的唯一标示
            categorys.setActions([action1, action2], forContext: UIUserNotificationActionContext.Default)
   
        let categories: NSSet = NSSet.init(object: categorys)
        
        let type7: UIRemoteNotificationType = [ UIRemoteNotificationType.Alert, UIRemoteNotificationType.Badge, UIRemoteNotificationType.Sound]
            
        let type8: UIUserNotificationType = [ UIUserNotificationType.Alert, UIUserNotificationType.Badge, UIUserNotificationType.Sound]
        
        UMessage.registerForRemoteNotifications(categories as? Set<UIUserNotificationCategory>, withTypesForIos7: type7, withTypesForIos8: type8)
        
       
            
         //分享
        /**
         *  设置ShareSDK的appKey，如果尚未在ShareSDK官网注册过App，请移步到http://mob.com/login 登录后台进行应用注册，
         *  在将生成的AppKey传入到此方法中。
         *  方法中的第二个参数用于指定要使用哪些社交平台，以数组形式传入。第三个参数为需要连接社交平台SDK时触发，
         *  在此事件中写入连接代码。第四个参数则为配置本地社交平台时触发，根据返回的平台类型来配置平台信息。
         *  如果您使用的时服务端托管平台信息时，第二、四项参数可以传入nil，第三项参数则根据服务端托管平台来决定要连接的社交SDK。
         */
        
        ShareSDK.registerApp(k_MOB_KEY,
                             //新浪微博、qq空间、qq好友、微信朋友圈、微信好友
                             activePlatforms: [SSDKPlatformType.TypeSinaWeibo.rawValue,
                                SSDKPlatformType.TypeQQ.rawValue,
                               SSDKPlatformType.TypeWechat.rawValue,],
                             onImport: {(platform : SSDKPlatformType) -> Void in
                                
                                switch platform{
                                case SSDKPlatformType.TypeSinaWeibo:
                                    ShareSDKConnector.connectWeibo(WeiboSDK.classForCoder())
                                case SSDKPlatformType.TypeWechat:
                                    ShareSDKConnector.connectWeChat(WXApi.classForCoder())
                                case SSDKPlatformType.TypeQQ:
                                    ShareSDKConnector.connectQQ(QQApiInterface.classForCoder(), tencentOAuthClass: TencentOAuth.classForCoder())
                              
                                default:
                                    break
                                }
            },
                             onConfiguration: {(platform : SSDKPlatformType,appInfo : NSMutableDictionary!) -> Void in
                                switch platform {
                                    
                                case SSDKPlatformType.TypeSinaWeibo:
                                    //设置新浪微博应用信息,其中authType设置为使用SSO＋Web形式授权
                                    appInfo.SSDKSetupSinaWeiboByAppKey(k_SING_KEY,
                                        appSecret : k_SING_KEY_AppMasterSecret,
                                        redirectUri : "http://www.sina.com",
                                        authType : SSDKAuthTypeBoth)
                                   
                                   
                                case SSDKPlatformType.TypeWechat:
                                    //设置微信应用信息
                                appInfo.SSDKSetupWeChatByAppId(k_weixin_APPID, appSecret: k_weixin_KEY_AppMasterSecret)
                                    
                                case SSDKPlatformType.TypeQQ:
                                    //设置QQ应用信息
                                    appInfo.SSDKSetupQQByAppId(k_TENCEN_APPID,
                                        appKey : k_TENCENT_AppMasterSecret,
                                        authType : SSDKAuthTypeWeb)
                                default:
                                    break
                                    
                                }
        })
        
        return true
    }
    
    func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
        
        UMessage.registerDeviceToken(deviceToken)
        
        let token = "\(deviceToken.description.stringByReplacingOccurrencesOfString("<", withString: "").stringByReplacingOccurrencesOfString(">", withString: "").stringByReplacingOccurrencesOfString(" ", withString: ""))"
        
        NSUserDefaults.standardUserDefaults().setObject(token, forKey: "k_UD_token")
        
        NSUserDefaults.standardUserDefaults().synchronize()
        
        print("\(token)")
        
    }
    
    func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
        
        //print("didFailToRegisterForRemoteNotificationsWithError===\(error)")
    }
    
    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
        
        UMessage.didReceiveRemoteNotification(userInfo)
    
    }
    
    func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
        return true
       
    }
   
    func application(application: UIApplication, handleOpenURL url: NSURL) -> Bool {
      
        return true
    }
    
    func didReceiveWeiboRequest(request: WBBaseRequest) {
        
    }
    
    //网络改变出发的事件
    func reachabilityChanged(note: NSNotification) {
        let reachability = note.object as! Reachability
        
        if reachability.isReachable() {//判断网路是否可用
            if isNetwork {
                //在断网重连网络后显示
                //SVProgressHUD.showInfoWithStatus("网络已连上!")
                print("网络已连上!")
                if reachability.isReachableViaWiFi() {
                    NSUserDefaults.standardUserDefaults().setBool(true, forKey:"iswifi")
                    NSUserDefaults.standardUserDefaults().synchronize()
                    SVProgressHUD.showInfoWithStatus("连接类型：WiFi")
                    
                } else if reachability.isReachableViaWWAN() {
                    NSUserDefaults.standardUserDefaults().setBool(false, forKey:"iswifi")
                    NSUserDefaults.standardUserDefaults().synchronize()
                    
                    SVProgressHUD.showInfoWithStatus("连接类型：移动网络")
                } else {
                     SVProgressHUD.showInfoWithStatus("连接类型：没有网络连接")
                }

            }
        }else
        {
            SVProgressHUD.showInfoWithStatus("网络已断开!")
            isNetwork = true
        }
    }

    func isLogin() -> Bool {
        return NSUserDefaults.standardUserDefaults().boolForKey("k_UD_isLogin")
    }
    func isComplete() -> Bool {
        return NSUserDefaults.standardUserDefaults().boolForKey("k_UD_isComplete")
    }
    func isWifi() -> Bool{
        return NSUserDefaults.standardUserDefaults().boolForKey("iswifi")
    }
    func isAutolive() -> Bool{
        return NSUserDefaults.standardUserDefaults().boolForKey("video_of_on")
    }
    func fontSize() -> String{
        return  NSUserDefaults.standardUserDefaults().stringForKey("fontSizeDefaut")!
    }

    func selectedChanelName() -> String{
        return NSUserDefaults.standardUserDefaults().stringForKey("selectedChanelName")!
    }
    
    func setHUDStyle() {
          SVProgressHUD.setDefaultStyle(SVProgressHUDStyle.Custom)
          SVProgressHUD.setFont(UIFont.systemFontOfSize(14))
          SVProgressHUD.setForegroundColor(UIColor.whiteColor())
          SVProgressHUD.setBackgroundColor(UIColor(red: 22 / 255.0, green: 22 / 255.0, blue: 22 / 255.0, alpha: 0.7))
          SVProgressHUD.setRingThickness(1.5)

    }
}

// 版权属于原作者
// http://code4app.com (cn) http://code4app.net (en)
// 发布代码于最专业的源码分享网站: Code4App.com